package org.jeecg.modules.demo.com.kunpeng.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.com.kunpeng.entity.*;
import org.jeecg.modules.demo.com.kunpeng.ex.ServiceCode;
import org.jeecg.modules.demo.com.kunpeng.ex.ServiceException;
import org.jeecg.modules.demo.com.kunpeng.service.ISaleContractService;
import org.jeecg.modules.demo.com.kunpeng.entity.dto.SaleContractKeyWordsQueryDTO;
import org.jeecg.modules.demo.com.kunpeng.mapper.ProjectMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.SaleContractCollectionPlanMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.SaleContractDetailMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.SaleContractMapper;
import org.jeecg.modules.demo.com.kunpeng.service.ICustomerInformationService;
import org.jeecg.modules.demo.com.kunpeng.vo.CustomerInformationPage;
import org.jeecg.modules.demo.com.kunpeng.vo.ProjectStandardVO;
import org.jeecg.modules.demo.com.kunpeng.vo.SaleContractVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 销售合同表
 * @Author: jeecg-boot
 * @Date:   2022-12-03
 * @Version: V1.0
 */
@Service
@Slf4j
public class SaleContractServiceImpl extends ServiceImpl<SaleContractMapper, SaleContract> implements ISaleContractService {

	@Autowired
	private SaleContractMapper saleContractMapper;
	@Autowired
	private SaleContractCollectionPlanMapper saleContractCollectionPlanMapper;
	@Autowired
	private SaleContractDetailMapper saleContractDetailMapper;
	@Autowired
	private ProjectMapper projectMapper;
	@Autowired
	private ICustomerInformationService customerInformationService;

	/**
	 * 分别插入销售合同表，销售合同收款计划表，销售合同详情表数据
	 * @param saleContract
	 * @param saleContractCollectionPlanList
	 * @param saleContractDetailList
	 */
	/*List<SaleContractCollectionPlan> saleContractCollectionPlanList*/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(SaleContract saleContract, List<SaleContractCollectionPlan> saleContractCollectionPlanList, List<SaleContractDetail> saleContractDetailList, CustomerInformation customerInformation) {
		List<SaleContract> saleContracts = saleContractMapper.selectBySaleContactName(saleContract.getContractName());
		if(saleContracts.size()>0){
			String message="该合同名已存在，请重新填写！";
			log.info(message);
			throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
		}
		if(saleContract.getContractAmount()==null || saleContract.getTaxPoint()==null){
			String message="请输入必填字段！";
			log.info(message);
			throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
		}
		saleContract.setStatus("0");
		saleContractMapper.insert(saleContract);
		System.out.println("saleContract:***"+saleContract.toString());
		log.info("销售合同表数据插入成功！");
		customerInformation.setMainId(saleContract.getId());
		CustomerInformationPage customerInformationPage=new CustomerInformationPage();
		BeanUtils.copyProperties(customerInformation,customerInformationPage);
		customerInformationService.insert(customerInformationPage);
		log.info("客户表数据插入成功！");
		if(saleContractCollectionPlanList!=null && saleContractCollectionPlanList.size()>0) {
			for(SaleContractCollectionPlan entity:saleContractCollectionPlanList) {
				//entity的值传给自己定义的对象
				/*System.out.println("entityId:****"+entity.getId());*/
				SaleContractCollectionPlan saleContractCollectionPlan=new SaleContractCollectionPlan();
				saleContractCollectionPlan.setAgreedCollectionTime(entity.getAgreedCollectionTime());
				saleContractCollectionPlan.setBatch(entity.getBatch());
				saleContractCollectionPlan.setCollectionProportion(entity.getCollectionProportion());
				saleContractCollectionPlan.setAmountCollected(entity.getAmountCollected());
				//外键设置
				//给销售合同表id赋值，插入销售合同收款计划表
				saleContractCollectionPlan.setScid(saleContract.getId());
				saleContractCollectionPlanMapper.insert(saleContractCollectionPlan);
				log.info("销售合同收款计划表数据插入成功！");
			}
		}

		if(saleContractDetailList!=null && saleContractDetailList.size()>0) {
			for(int i=0;i<saleContractDetailList.size();i++) {

				//添加项目时未关联合同编号则修改项目表合同编号
				Project pj = projectMapper.listProjectByProjectName(saleContractDetailList.get(i).getProjectName());
				if(null!=pj){
					log.info("projects:"+pj.toString());
					if(null==pj.getAgreementId() || pj.getAgreementId().length()==0 || pj.getAgreementId()=="" || pj.getAgreementId().equals("")){
						log.info("项目id："+pj.getId()+"合同编号："+saleContract.getContractId());
						projectMapper.updateAgreementIdById(pj.getId(),saleContract.getContractId());
					}else {
						throw new ServiceException(ServiceCode.ERR_CONFLICT,"项目：【"+pj.getProjectName()+"】已存在关联合同,请重新选择！");
					}
				}

				//插入项目id
				ProjectStandardVO projectStandardVO = projectMapper.selectByProjectId(saleContractDetailList.get(i).getProjectId());
				//如果该合同存在关联的项目，set项目id
				if(projectStandardVO!=null){
					System.out.println("projectStandardVO:"+projectStandardVO.toString());
					System.out.println("entity:"+saleContractDetailList.get(i).toString());
					saleContractDetailList.get(i).setPjid(projectStandardVO.getId());
				}
				saleContractDetailList.get(i).setScid(saleContract.getId());
				saleContractDetailMapper.insert(saleContractDetailList.get(i));
				log.info("销售合同详情表插入成功！");
			}
		}
	}

	/**
	 * 修改销售合同表数据及其他表的关联数据
	 * @param saleContract
	 * @param saleContractCollectionPlanList
	 * @param saleContractDetailList
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(SaleContract saleContract,List<SaleContractCollectionPlan> saleContractCollectionPlanList,List<SaleContractDetail> saleContractDetailList) {
		saleContractMapper.updateById(saleContract);
		
		//1.先删除子表数据
		saleContractCollectionPlanMapper.deleteByMainId(saleContract.getId());
		saleContractDetailMapper.deleteByMainId(saleContract.getId());
		
		//2.子表数据重新插入
		if(saleContractCollectionPlanList!=null && saleContractCollectionPlanList.size()>0) {
			for(SaleContractCollectionPlan entity:saleContractCollectionPlanList) {
				//外键设置
				entity.setId(null);
				entity.setScid(saleContract.getId());
				saleContractCollectionPlanMapper.insert(entity);
			}
		}
		if(saleContractDetailList!=null && saleContractDetailList.size()>0) {
			for(SaleContractDetail entity:saleContractDetailList) {
				//外键设置
				List<SaleContractDetail> saleContractDetails = saleContractDetailMapper.selectByMainId(saleContract.getId());
				//验证项目是否重复
				if(saleContractDetails.size()>0){
					for(SaleContractDetail saleContractDetail:saleContractDetails){
						if(saleContractDetail.getProjectName().equals(entity.getProjectName())){
							String message="项目【"+saleContractDetail.getProjectName()+"】已关联合同【"+saleContract.getContractName()+"】,请重新填写！";
							throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
						}
					}
				}

				ProjectStandardVO projectStandardVO = projectMapper.selectByProjectId(entity.getProjectId());
				//如果该合同存在关联的项目，set项目id
				if(projectStandardVO!=null){
					System.out.println("projectStandardVO:"+projectStandardVO.toString());
					System.out.println("entity:"+entity.toString());
					entity.setPjid(projectStandardVO.getId());
				}
				entity.setId(null);
				entity.setScid(saleContract.getId());
				saleContractDetailMapper.insert(entity);
			}
		}
	}

	/**
	 * 根据销售合同id删除关联数据
	 * @param id
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		saleContractCollectionPlanMapper.deleteByMainId(id);
		saleContractDetailMapper.deleteByMainId(id);
		saleContractMapper.deleteById(id);
	}

	/**
	 * 根据销售合同id批量删除关联数据
	 * @param idList
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			saleContractCollectionPlanMapper.deleteByMainId(id.toString());
			saleContractDetailMapper.deleteByMainId(id.toString());
			saleContractMapper.deleteById(id);
		}
	}

	/**
	 * 根据关键字查询数据
	 * @param page
	 * @param saleContractKeyWordsQueryDTO
	 * @return
	 */
	@Override
	public Page<SaleContractVO> listByKeyWords(Page<SaleContractVO> page, SaleContractKeyWordsQueryDTO saleContractKeyWordsQueryDTO) {
		log.info("开始处理根据关键字查询数据表信息：service");
		Page<SaleContractVO> list = page.setRecords(saleContractMapper.listByKeyWords(page, saleContractKeyWordsQueryDTO.getContractProperties(), saleContractKeyWordsQueryDTO.getStatus(),
				saleContractKeyWordsQueryDTO.getKeyWords()));
		//遍历销售合同
		for (SaleContractVO saleContract:list.getRecords()) {
			/*System.out.println("销售合同数据：" + saleContract.toString());*/
			Double contractAmount = saleContract.getContractAmount().doubleValue();
			//销售合同不含税金额
			saleContract.setNoTaxAmount(new BigDecimal(contractAmount - (contractAmount * saleContract.getTaxPoint())));
			List<SaleContractCollectionPlan> saleContractCollectionPlans = saleContractCollectionPlanMapper.selectByMainId(saleContract.getId());
			if (saleContractCollectionPlans.size() > 0) {
				BigDecimal returnAmount = new BigDecimal(0.00);
				for (SaleContractCollectionPlan saleContractCollectionPlan : saleContractCollectionPlans) {
					/*System.out.println("销售合同收款计划数据：" + saleContractCollectionPlan.toString());*/
					Long nowTimeMillis = System.currentTimeMillis();
					Calendar cal = Calendar.getInstance();
					cal.setTime(saleContractCollectionPlan.getAgreedCollectionTime());
					Long collectionMillis = cal.getTimeInMillis();
					if (nowTimeMillis > collectionMillis) {
						returnAmount = returnAmount.add(saleContractCollectionPlan.getAmountCollected());
					}
				}
				//销售合同回款金额
				saleContract.setReturnAmount(returnAmount);
				//销售合同未回款金额
				saleContract.setNoReturnAmount(saleContract.getNoTaxAmount().subtract(returnAmount));
			}
			/*if (!(saleContract.getContractStartTime() == null || saleContract.getContractEndTime() == null)) {
				long nowTimeMillis = System.currentTimeMillis();
				Calendar cal = Calendar.getInstance();
				cal.setTime(saleContract.getContractStartTime());
				long startTimeMillis = cal.getTimeInMillis();
				cal.setTime(saleContract.getContractEndTime());
				Long endTimeMillis = cal.getTimeInMillis();
				Long seTime = endTimeMillis - startTimeMillis;
				Long snTime = nowTimeMillis - startTimeMillis;
				if (snTime > seTime) {
					saleContract.setStatus("已完成");
					saleContractMapper.updateStateById(saleContract.getId(),"3");
				} else if (startTimeMillis > nowTimeMillis) {
					saleContract.setStatus("未开始");
					saleContractMapper.updateStateById(saleContract.getId(), "1");
				} else if (seTime > snTime) {
					saleContract.setStatus("执行中");
					saleContractMapper.updateStateById(saleContract.getId(), "2");
				}
			}*/
			String status = saleContract.getStatus();
			switch (status){
				case "0":saleContract.setStatus("待审批");
					break;
				case "1":saleContract.setStatus("已审批");
					break;
				case "2":saleContract.setStatus("中止");
					break;
				case "3":saleContract.setStatus("作废");
					break;
			}
		}
		try {
			if(list.getRecords().size()==0);
		} catch (Exception e) {
			Result.error("数据不存在，请重新输入！");
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 根据项目名称销售合同数据
	 * @param projectName
	 * @return
	 */
	@Override
	public SaleContractVO selectByProjectName(String projectName) {
		SaleContractVO saleContractVO = saleContractMapper.selectByProjectName(projectName);
		return saleContractVO;
	}

	/**
	 * 根据合同编号获取合同列表
	 * @param saleContractId
	 * @return
	 */
	@Override
	public List<SaleContractVO> selectBySaleContractId(String saleContractId) {
		List<SaleContractVO> saleContractVOS = saleContractMapper.selectBySaleContractId(saleContractId);
		return saleContractVOS;
	}

	/**
	 * 根据id修改关联项目名称
	 * @param id
	 * @param projectName
	 */
	@Override
	public void updateProjectNameById(String id, String projectName) {
		saleContractMapper.updateProjectNameById(id,projectName);
	}

	/**
	 * 销售合同名称列表
	 * @return
	 */
	@Override
	public List<String> saleContractNameList() {
		List<String> saleContractNameList = saleContractMapper.saleContractNameList();
		return saleContractNameList;
	}

	/**
	 * 根据合同名称获取合同编号
	 * @param saleContractName
	 * @return
	 */
	@Override
	public String selectSaleContractIdBySaleContractName(String saleContractName) {
		String saleContractId = saleContractMapper.selectSaleContractIdBySaleContractName(saleContractName);
		return saleContractId;
	}

	/**
	 * 根据id修改合同状态
	 * @param id
	 * @param status
	 */
	@Override
	public void updateStateById(String id, String status) {
		saleContractMapper.updateStateById(id,status);
	}
}
